import * as THREE from './three.weapp.min.js'
import {
  OrbitControls
} from './OrbitControls'

Page({
  data: {
    canvasId: null
  },
  onLoad() {
    wx.createSelectorQuery().select('#c').node().exec(res => {
      const canvas = THREE.global.registerCanvas(res[0].node)

      this.setData({
        canvasId: canvas._canvasId
      })
      const camera = new THREE.PerspectiveCamera(60, canvas.width / canvas.height, 1, 1000); // 可视角度，宽高比，近端距离，远端距离
      const scene = new THREE.Scene();
      const renderer = new THREE.WebGLRenderer({
        antialias: true
      });

      renderer.setPixelRatio(2)
      const controls = new OrbitControls(camera, renderer.domElement);
      // 将相机正对前方
      camera.position.set(-0.1, 2, -5);
      // 自动旋转视角
      controls.autoRotate = true;
      // 旋转速度 60 / 0.618 圈/秒
      controls.autoRotateSpeed = 0.618;
      // 控制镜头缩放，这里禁用了，因为是用正方体做的 除非能解决正方体的大小问题
      controls.enableZoom = false
      // 惯性滑动
      controls.enableDamping = true
      controls.update();

      var sides = ['右.jpg', '左.jpg','上.jpg', '下.jpg','前.jpg', '后.jpg']

      var materials = [];
      for (var i = 0; i < sides.length; i++) {
        var side = sides[i];
        var texture = new THREE.TextureLoader().load(side);
        materials.push(new THREE.MeshBasicMaterial({
          map: texture
        }));
      }

      var mesh = new THREE.Mesh(new THREE.BoxBufferGeometry(canvas.height, canvas.height, canvas.height), materials);
      mesh.geometry.scale(-1, 1, 1);

      scene.add(mesh);

      function render() {
        canvas.requestAnimationFrame(render);
        controls.update();
        renderer.render(scene, camera);
      }
      render()
    })
  },
  onUnload: function() {
    THREE.global.unregisterCanvas(this.data.canvasId)
  },
  touchStart(e) {
    THREE.global.touchEventHandlerFactory('canvas', 'touchstart')(e)
  },
  touchMove(e) {
    THREE.global.touchEventHandlerFactory('canvas', 'touchmove')(e)
  },
  touchEnd(e) {
    THREE.global.touchEventHandlerFactory('canvas', 'touchend')(e)
  }
})